/* eslint-disable @typescript-eslint/dot-notation */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useRef } from 'react'
import { XoProTable } from '@/components/XoProTable';
import ProCard from '@ant-design/pro-card';
import { Col, RadioChangeEvent, UploadProps } from 'antd';
import { message } from 'antd';
import { Radio, Space, Row, Button, Tooltip } from 'antd';
import styles from './index.less';
import _ from 'lodash'
import {
  DrawerForm, ProFormSelect, ProFormRadio, ModalForm, ProFormText, ProFormTextArea, ProFormUploadButton
} from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { useState } from 'react';
import StudentInfo from '../StudentInfo';
import { batchModifyRealNameTemplate, exportFile, getgroupOption, getInfoByStepType, importFile } from '@/services/student';
import { getStudentStatusCount } from '@/services/student';
import { getStudentList } from '@/services/student';
import { history } from 'umi';
import { useEffect } from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { exportUtils } from '@/utils/export';
import { addUserAnalysisByGroupIds, addUserAnalysisCountByUids, addUserReviewCountByGroupIds, addUserReviewCountByUids, listByPhones } from '@/services/goku';

import { onRequestNickName } from '@/utils/requestPhone';
import { courseItemExport } from '@/services/situation';
import moment from 'moment';
type GithubIssueItem = {
  liveTotalCount?: number
  id?: string
  liveAttendanceCount?: number
  missLiveCount?: number
  videoAttendanceCount?: number
  nickname?: string
};
interface Params {
  dataInfo: any
}
export default function StudentList(props: Params) {
  const [shiwForm, setShowForm] = useState<boolean>(false);
  const [show, setShowModal] = useState<boolean>(false);
  const [idx, setIndex] = useState<number>();
  const [ids, setUserId] = useState<any>();
  const [ids3, setId] = useState<any>();
  const [lock, setUnlock] = useState<any>();
  const [item1, setItemList] = useState<any[]>([]);
  const [typeList, setTypeList] = useState<any>();
  const [status, setStatus] = useState<any>();
  const [state, setState] = useState<any>();
  const [userType, setUserType] = useState<any>('a');
  const [sendType, setSendType] = useState<any>('c');
  const [option, setGroupOption] = useState<any>();
  const [optionsValue, setOptionValue] = useState<any>();
  const [phoneValue, setPhoneValue] = useState<any>();
  const [ruleObj, setRuleObj] = useState<any>({ rule: '', help: '' });
  const [resfrest, setRefrest] = useState<boolean>(false)
  const [ipt, setIptValue] = useState<any>();
  const [count, setCount] = useState<any>(0);
  const { dataInfo } = props;
  const [showImport, setShowImportModel] = useState<boolean>(false)
  const [showError, setshowError] = useState<boolean>(false)
  const [uploadRule, setUploadRule] = useState<any>({ rule: '', help: "" })
  const [datain, setDataInfo] = useState<any>({})
  const [file, setFile] = useState();
  const uref = useRef<ActionType>()
  const showForm = async (re: any, index: number) => {
    setIndex(index)
    setShowForm(true);
  }
  const ref = useRef<ActionType>();
  const { id } = history.location.query || {}
  useEffect(() => {
    (async () => {
      const res = await getStudentStatusCount({ activityId: id });
      setState(res?.result?.[0]?.status)
      setStatus(res?.result)
      setRefrest(true);
    })();

    (async () => {
      const res = await getInfoByStepType({ id: id });
      setUnlock(res?.result);
      setTypeList(res?.result?.typeList)
    })();
    (async () => {
      const res = await getgroupOption({ activityId: id, pageSize: -1 })
      const res1 = res.result?.map((item: any) => {
        return { label: item.name, value: item.id }
      })
      setGroupOption(res1)
    })()
  }, [])

  const onReset = () => {
    setPhoneValue('')
    setOptionValue('')
  }
  const getTotal = (data: any[], getItem: (item: any) => any) => {
    return data?.map((item) => {
      return getItem(item);
    })?.reduce((total, value) => {
      return total + value
    }, 0) ?? 0;
  }
  const [loading, setLoading] = useState<boolean>(false)

  const typeList1 = typeList?.filter((item: any) => {
    return item.type == 0 || item.type == 6
  })

  const typeList2 = typeList?.filter((item: any) => {
    return item.type == 4;
  })
  const problemTotal = getTotal(typeList2, (item) => item.count);
  const CourseTotal = getTotal(typeList1, (item) => item.count);
  const showModal = (record: any, type: number) => {
    setShowModal(true);
    if (type == 2) {
      setIptValue(record?.phone)
      if (ipt == '') return;
      setCount(1)
    } else {
      setIptValue('')

    }
    // setClickType(type);
    // setUserPhone(record?.phone);
  }

  const onChange = (e: any) => {
    const val = e.target.value

    setIptValue(val.replace(/[^\d\n]/g, ""))
    const arr = val.split('\n');
    arr?.forEach((item: any, index: any) => {
      if (!item) {
        //删除结尾为空的元素
        arr.splice(index, 1)
      }
    })
    setCount(arr?.length)
    // const countVal: number = val.replace(/[\n]/g, "").length
    const reg = /[^\d.\n]+/;
    const reg1 = /[0-9\n.]+$/
    const reg2 = /^[1]\d{10}$/
    if (ipt != '' && reg.test(ipt)) {
      setRuleObj({ rule: 'error', help: '手机号仅可输入数字，请检查输入' })
      return
    } else if (ipt != '' && ipt && !reg1.test(ipt)) {
      setRuleObj({ rule: 'error', help: '输入内容非数字结尾，请检查输入' })
      return
    } else if (arr.length > 500) {
      setRuleObj({ rule: 'error', help: `单次做多支持500个用户批量操作` })
      return;
    } else if (val) {

      const item = arr?.every((item: any) => {
        item.replace(/[^\d\n]/g, "")
        return reg2.test(item)
      })

      if (!item) {
        setRuleObj({ rule: 'error', help: '下列手机号格式不正确' });
      } else {
        setRuleObj({ rule: '', help: '' });
      }
    } else {
      setRuleObj({ rule: '', help: '' })
    }
  }


  const columns1: ProColumns[] = [
    {
      dataIndex: 'errorPhone',
      title: '手机号',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      dataIndex: 'errorRealName',
      title: '真实姓名',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      dataIndex: 'errorMsg',
      title: '失败原因',
      align: 'center',
      search: false,
      ellipsis: true,
    },
  ]
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      dataIndex: 'uid',
      title: '用户ID',
      search: false,
      ellipsis: true,
      fixed: 'left',
      width: 80,
    },
    {
      dataIndex: 'nickname',
      title: '用户昵称',
      ellipsis: true,
      align: 'center',
      search: false,
      render: (text, record, index) => (
        <a onClick={() => showForm(record, index)}>{record?.nickname || '-'}</a>
      )
    },
    {
      dataIndex: 'uid',
      hideInTable: true,
      title: '昵称/手机号',
      ellipsis: true,
      align: 'center',
      renderFormItem: () => {
        return (
          <div className={styles.search}>
            <ProFormSelect
              wrapperCol={{ span: 24 }}
              labelCol={{ span: 24 }}
              name="uid"
              showSearch
              fieldProps={{
                onChange: (val) => setPhoneValue(val)
              }}
              labelAlign="left"
              debounceTime={500}
              placeholder="请选择"
              request={onRequestNickName}
            />
          </div>
        );
      },
    },
    {
      dataIndex: 'realName',
      title: '真实姓名',
      search: false,
      align: 'center',
      // width: 120,
      ellipsis: true,

    },
    {
      dataIndex: 'phone',
      title: '手机号',
      align: 'center',
      width: 120,
      search: false,
      ellipsis: true,

    },
    {
      dataIndex: 'groupName',
      title: '班级',
      align: 'center',
      ellipsis: true,
      renderFormItem: () => {
        return (
          <div className={styles.search}>
            <ProFormSelect
              wrapperCol={{ span: 24 }}
              labelCol={{ span: 24 }}
              fieldProps={{
                onChange: (val) => setOptionValue(val)
              }}
              name="groupId"
              labelAlign="left"
              placeholder="请选择"
              options={option}
            />
          </div>
        );
      },
    },
    {
      dataIndex: 'teacherName',
      title: '辅导老师',
      search: false,
      align: 'center',
      ellipsis: true,

      // width: 120,
    },
    {
      dataIndex: 'liveAttendanceCount',
      title: (
        <>
          直播课到课率
          <Tooltip placement="top" title={`出勤/观看回放/缺勤，已开${CourseTotal || 0}课`}>
            <QuestionCircleOutlined style={{ marginLeft: 4 }} />
          </Tooltip>
        </>
      ),
      search: false,
      align: 'center',
      width: 160,
      ellipsis: true,
      render: (text, record) => {
        const liveAttendanceCount = record.liveAttendanceCount || 0;
        const videoAttendanceCount = record.videoAttendanceCount || 0;
        const liveTotalCount = record.liveTotalCount || 0;
        const missLiveCount = record.missLiveCount || 0;
        const totalAttendanceCount = liveAttendanceCount + videoAttendanceCount
        const percent = totalAttendanceCount ? ((totalAttendanceCount / liveTotalCount) * 100).toFixed(2) : 0;
        const str = `${percent}% (${liveAttendanceCount} / ${videoAttendanceCount} / `
        return <Tooltip placement="top" title={`${str}${missLiveCount}`}>
          <span>{str}<span style={{ color: 'red' }}>{missLiveCount})</span></span>
        </Tooltip>
      }
    },
    {
      dataIndex: 'completeItemCount',
      title: (
        <>
          条目完成率
          <Tooltip placement="top" title={`已解锁${lock?.itemUnlockCount || 0}个条目`}>
            <QuestionCircleOutlined style={{ marginLeft: 4 }} />
          </Tooltip>
        </>
      ),
      search: false,
      align: 'center',
      width: 160,
      ellipsis: true,
      render: (text, record: any) => {

        const completeItemCount = record.completeItemCount || 0;
        const unlockItemCount = record.unlockItemCount || 0;
        const percent = completeItemCount ? ((completeItemCount / unlockItemCount) * 100).toFixed(2) : 0;
        const str = `${percent}% (${completeItemCount} / ${unlockItemCount})`;
        return <Tooltip placement="top" title={str}>
          <span>{str}</span>
        </Tooltip>

      }
    },
    {
      dataIndex: 'completeStepCount',
      title: (
        <>
          练习题完成率
          <Tooltip placement="top" title={`已解锁${lock?.itemUnlockCount || 0}个条目，${problemTotal || 0}个练习题`}>
            <QuestionCircleOutlined style={{ marginLeft: 4 }} />
          </Tooltip>
        </>
      ),
      search: false,
      align: 'center',
      width: 160,
      ellipsis: true,
      render: (text, record: any) => {
        const completeStepCount = record.completeStepCount || 0;
        const incompleteStepCount = record.incompleteStepCount || 0;
        const percent = completeStepCount ? ((completeStepCount / (incompleteStepCount + completeStepCount)) * 100).toFixed(2) : 0;

        const str = `${percent}% (${completeStepCount} / ${incompleteStepCount + completeStepCount})`
        return <Tooltip placement="top" title={str}>
          <span>{str}</span>
        </Tooltip>
      }
    },
    lock?.enableGame == 1 ? {
      dataIndex: 'playGradeName',
      title: '棋士品级',
      search: false,
      ellipsis: true,

      align: 'center',
      // width: 100,
    } :
      {
        hideInTable: true, search: false,
      },
    lock?.enableGame == 1 ? {
      dataIndex: 'playScore',
      title: '棋灵对弈积分',
      search: false,
      align: 'center',
      width: 150,
      ellipsis: true,

    } : {
      hideInTable: true,
      search: false,
    },
    lock?.aiGoFlag == 1 ? {
      dataIndex: 'gokuCurPower',
      title: '悟空战力',
      search: false,
      align: 'center',
      // width: 150,
      ellipsis: true,

    } : {
      hideInTable: true,
      search: false,
    },
    lock?.aiGoFlag == 1 ? {
      dataIndex: 'gokuCurScore',
      title: '悟空分数',
      search: false,
      align: 'center',
      // width: 150,
      ellipsis: true,

    } : {
      hideInTable: true,
      search: false,
    },
    1 ? {
      dataIndex: 'gokuAnalysisCount',
      title: '点评次数',
      search: false,
      align: 'center',
      // width: 150,
      ellipsis: true,
      render: (text,) => (
        <span>{text || '-'}</span>
      )
    } : {
      hideInTable: true,
      search: false,
    },
    1 ? {
      dataIndex: 'gokuReviewCount',
      title: '复盘次数',
      search: false,
      align: 'center',
      ellipsis: true,
      render: (text) => (
        <span>{text || "-"}</span>
      )
    } : {
      hideInTable: true,
      search: false,
    },
    lock?.aiGoFlag == 1 ? {
      dataIndex: '',
      fixed: 'right',
      title: '操作',
      search: false,
      align: 'center',
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => showModal(record, 2)}>添加点评&复盘</a>
      )
    } : {
      hideInTable: true,
      search: false,
    },
  ]
  const changeStatus = (e: RadioChangeEvent) => {
    setState(e.target.value)
  }
  const exportList = async () => {
    const params = {
      activityId: id,
      groupId: optionsValue,
      uid: phoneValue,
      status: state
    }
    if (item1?.length == 0) {
      message.destroy();
      message.error('没有可导出的数据');
      return;
    }
    setLoading(true);
    await courseItemExport({
      exportType: 'exportActivityUsers',
      map: {
        ...params
      },
      fileName: `${dataInfo?.name} ${moment(new Date()).format('YYYY-MM-DD HH时mm分ss秒')}.xlsx`

    });
    setLoading(false);
  }

  const onchange = (e: any) => {
    setUserType(e.target.value)
  }
  const onchange1 = (e: any) => {
    setSendType(e.target.value)
  }

  const showImportModel = () => {
    setShowImportModel(true)
  }

  // 导入
  const propItem: UploadProps = {
    name: 'import',
    accept: ".xlsx,application/vnd.ms-excel",
    maxCount: 1,
    headers: {
      "Content-Type": "multipart/form-data;charset=utf-8"
    },
    beforeUpload(file, fileList) {
      if (!file || file.name.split('.')[1] !== 'xlsx') {
        setUploadRule({ rule: 'error', help: '请上传xlsx后缀的文件' })
        return false;
      }
      setUploadRule({ rule: '', help: '' })
      return true;
    },
    async customRequest(value: any) {
      const { file } = value;
      // const res = await importsExcel(file)
      // 添加企业文件接口
      setLoading(true)
      const data = await importFile(file);
      if (data.success) {
        setDataInfo(data.result)
        setFile(file)
        value?.onSuccess(data, file);
        message.success('批量导入用户真实姓名成功')

      } else {
        if (data.code == 2004 || data.code == 2005 || data.code == 2006) {
          message.error(data?.message)
          setUploadRule({ rule: '', help: data?.message })
          value?.onError(data, file);
          setLoading(false)
          return;
        }
        value?.onError(data, file);
      }
      setLoading(false)
      return
    },
    onChange(info) {
      console.log(info);

      if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList);
      }

    },
  };

  // 下载
  const download = async () => {
    const res = await batchModifyRealNameTemplate({})
    exportUtils(res, '用户真实姓名导入模板');
  }



  const downloadErrorData = async () => {
    const data = await exportFile({ failList: datain?.failList });
    exportUtils(data, '导入失败明细');
    message.success('下载数据成功')

  }

  const noUserListCenter = (res: any) => {
    const arr = res?.notExistUserList?.filter((item: any) => {
      return item.uid != null
    })
    if (arr && arr.length !== 0) {
      let str = ''
      arr?.map((item: any) => {
        if (str == '') {
          str += item?.phone
        } else {
          str = str + '、' + item?.phone;
        }
      })
      setRuleObj({ rule: 'error', help: `下列手机号的用户未在当前课程用户列表中(${str})` })
      return
    } else if (res?.notNormalUserList && res?.notNormalUserList?.length != 0) {
      let str = ''
      res?.notNormalUserList?.map((item: any) => {
        if (str == '') {
          str += item?.phone
        } else {
          str = str + '、' + item?.phone;
        }
      })
      setRuleObj({ rule: 'error', help: `下列手机号用户在读状态非正常、申请退费、调班进入状态，无法进行添加操作(${str})` })
      return
    } else {
      setRuleObj({ rule: '', help: `` })
    }
  }


  return (
    <div className={styles.student_wrap}>
      <ProCard className={styles.card} direction="column" ghost gutter={[0, 16]}>
        <Row align="middle" style={{ height: '100%', paddingLeft: '20.0064px' }} >
          <div>在读状态：</div>
          <Radio.Group onChange={changeStatus} value={state} buttonStyle="solid">
            <Space>
              {
                status?.map((item: any) => {
                  return <Radio.Button key={item.status} value={item.status}>{
                    item.status == 0 ? '正常' : item.status == 1 ? '已退费' : item.status == 2 ? '延期' : item.status == 3 ? '申请退费' : item.status == 4 ? "已调班" : item.status == 5 ? "调班进入" : ""
                  }{`(${item.count || 0})`}</Radio.Button>
                })
              }

            </Space>
          </Radio.Group>
        </Row>

      </ProCard>
      <XoProTable
        className={styles.table}
        style={{ marginTop: '15.9936px' }}
        rowKey="id"
        params={{
          status: state,
          resfrest
        }}
        onReset={onReset}
        actionRef={ref}
        columns={columns}
        request={async (params1: any) => {
          (async () => {
            const result = await getInfoByStepType({ id: id });
            setUnlock(result?.result);
            setTypeList(result?.result?.typeList)
          })();

          let res;
          if (params1?.status) {
            const result = await getInfoByStepType({ id: id });
            setUnlock(result?.result);
            setTypeList(result?.result?.typeList)

            res = await getStudentList({ ...params1, activityId: id })
            const ids1 = res.result?.records?.map((item: any) => {
              return item.uid
            })
            const ids2 = res.result?.records?.map((item: any) => {
              return item.id
            })
            setUserId(ids1)
            setId(ids2)
            setItemList(res?.result?.records)

          }

          return {
            data: res?.result?.records,
            total: res?.result?.total
          }

        }}
        scroll={{ x: 1700 }}
        hasIndex={false}
        toolBarRender={() => [
          lock?.aiGoFlag == 1 ? <Button key="4" onClick={() => showModal({}, 1)}>
            批量发放点评&复盘
          </Button> : null,
          // 1 ? <Button key="4" onClick={() => showModal({}, 1)}>
          //   批量发放点评&复盘
          // </Button> : null,
          <Button key="4" onClick={showImportModel}>
            导入用户真实姓名
          </Button>,
          <Button key="3" loading={loading} onClick={exportList}>
            导出
          </Button>,
        ]} />
      <DrawerForm
        className={styles.drawer_form}
        visible={shiwForm}

        width="80%"
        drawerProps={{
          footerStyle: { display: 'none' },
          closeIcon: false, bodyStyle: { padding: '0' }, destroyOnClose: true,
          onClose: () => ref.current?.reload()
        }}
        onVisibleChange={setShowForm}
      >
        <StudentInfo ids={ids} idx={idx} ids3={ids3} />
      </DrawerForm>
      <ModalForm
        title={'导入用户真实姓名'}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setShowImportModel(false),
        }}
        submitter={{
          render: (prop: any) => {
            return [
              <div key="btn">
                <Button key="back" onClick={() => setShowImportModel(false)} >
                  取消
                </Button>
                <Button key="submit"
                  type="primary"
                  loading={loading}
                  onClick={
                    () => {
                      prop.submit();
                      if (file && uploadRule.help == '' && datain?.failCount == 0) {
                        ref.current?.reload()
                        message.success('导入成功')
                      }
                    }
                  }>
                  确定
                </Button>
              </div>,
            ]
          }
        }}
        onFinish={async () => {
          console.log(file);

          if (file && datain.failCount == 0) {
            setShowImportModel(false)
          } else {
            setshowError(true)
          }
        }}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        layout="horizontal"
        visible={showImport}
        onVisibleChange={(val) => {
          setShowImportModel(val)
        }}
      >
        <div style={{ display: 'flex', alignItems: "flex-start" }}>
          <Col span={16}>
            <div style={{ display: "flex", justifyContent: 'end', marginRight: '20px' }}>
              <ProFormUploadButton
                name="upload"
                label="导入Excel"
                listType="text"
                title="选择上传的文件"
                style={{ width: '180px' }}
                rules={[
                  { required: true, message: '请选择上传的文件' },
                  {
                    validator: async (_, value) => {
                      if (value && uploadRule.help !== '') {
                        return Promise.reject(new Error(uploadRule.help));
                      }
                      return;
                    }
                  }
                ]}
                max={1}

                fieldProps={{
                  name: 'file',
                  ...propItem,
                  onRemove: (file) => {
                    setUploadRule({ rule: '', help: '' })
                  }
                }}
                // validateStatus={uploadRule?.rule}
                // help={uploadRule?.help}
                extra={
                  <a href="javascript:;" style={{ display: 'block' }} onClick={_.debounce(download, 1000)}>下载导入模板</a>
                }
              />
            </div>
          </Col>
          <Col span={8}>
            <span style={{ color: '#999', lineHeight: '32px' }}>只能上传Excel类型文件</span>
          </Col>
        </div>

      </ModalForm>
      <ModalForm
        title="异常数据"
        visible={showError}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setshowError(false),
        }}
        submitter={{
          resetButtonProps: {
            type: 'dashed',
          },
          submitButtonProps: {
            style: {
              display: 'none',
            },
          },
        }}
      >
        <div>{`本次共导入${datain?.allCount}条数据，成功${datain?.successCount}条，失败${datain?.failCount}条`}</div>
        <div style={{ marginTop: '10px' }}>导入失败明细</div>
        <XoProTable
          style={{ marginTop: '15.9936px' }}
          rowKey="id"
          bordered
          search={false}
          pagination={false}
          hasIndex={false}
          options={false}
          dataSource={datain?.failList}
          columns={columns1}
        />
        <a href="javascript:;" style={{ textAlign: 'right', display: 'block', marginRight: '20px' }} onClick={_.debounce(downloadErrorData, 1000)}>下载异常数据</a>
      </ModalForm>
      <ModalForm
        title='批量发放点评&复盘'
        submitter={{
          render: (prop: any) => {
            return [
              <div key="btn">
                <Button key="back" onClick={() => setShowModal(false)} >
                  取消
                </Button>
                <Button key="submit"
                  type="primary"
                  loading={loading}
                  onClick={
                    () => {
                      if (ipt == '') {
                        setRuleObj({ rule: 'error', help: `请输入发放的手机号` })
                      }
                      prop.submit();
                    }
                  }>
                  确定
                </Button>
              </div>,
            ]
          }
        }}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setRuleObj({ rule: '', help: '' })
            setUserType('a')
            setSendType('c')
          },

        }}
        className={styles.modal}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        layout="horizontal"
        visible={show}
        onVisibleChange={setShowModal}

        onFinish={async (values) => {
          const { mobile, sendCount } = values;
          if (mobile && mobile == '') {
            setRuleObj({ rule: 'error', help: `请输入发放的手机号` })
            return
          } else {
            setRuleObj({ rule: '', help: `` })
          }

          let registerUid, res, mobileArr;
          if (mobile) {
            mobileArr = mobile.split('\n').filter((item: string) => item != "")
            console.log(mobileArr);

            res = await listByPhones({ phoneList: mobileArr, courseId: id })
            const noregisterPhone = res?.result?.notExistUserList?.filter((item: any) => {
              return item.uid == null
            })
            registerUid = res?.result?.userList?.map((item: any) => {
              return item.uid
            })
            // const arr = mobileArr.filter((item: any) => {
            //   return !registerPhone.includes(item)
            // })
            if (noregisterPhone && noregisterPhone.length !== 0) {
              let str = ''
              noregisterPhone?.map((item: any) => {
                if (str == '') {
                  str += item?.phone
                } else {
                  str = str + '、' + item?.phone;
                }
              })
              setRuleObj({ rule: 'error', help: `手机号${str}未注册` })
              return;
            }
            (async () => {
              await noUserListCenter(res?.result)
            })()
          }
          const result = (res: any) => {
            if (res?.success) {
              message.success('发放成功');
              setShowModal(false);
              setUserType('a');
              setSendType('c');
              ref.current?.reload()
            }
          }
          if (res?.result?.notExistUserList?.length == 0 && res?.result?.notNormalUserList?.length == 0 && res?.result?.userList.length == mobileArr.length) {
            const params = {
              userIds: registerUid, count: sendCount, courseId: id
            }
            console.log(userType, sendType);

            if (userType == 'a' && sendType == 'c') {
              setLoading(true)
              const res = await addUserAnalysisCountByUids(params)
              setLoading(false)
              result(res)
            }
            else if (userType == 'a' && sendType == 'd') {
              setLoading(true)
              const res = await addUserReviewCountByUids({ ...params, courseId: id })
              setLoading(false)
              result(res)

            }
            ref.current?.reload();
          } else {
            const params1 = {
              courseId: id, count: sendCount
            }
            console.log(userType, sendType);
            if (userType == 'b' && sendType == 'c') {
              setLoading(true)
              const res = await addUserAnalysisByGroupIds(params1)
              setLoading(false)
              result(res)
            } else if (userType == 'b' && sendType == 'd') {
              setLoading(true)
              const res = await addUserReviewCountByGroupIds(params1)
              setLoading(false)
              result(res)
            }
          }

        }
        }
      >
        <ProFormRadio.Group
          name="radio-group"
          label="选择用户"

          fieldProps={{
            onChange: onchange,
          }}
          initialValue={"a"}
          rules={[
            { required: true, message: '请选择用户' }
          ]}
          options={[
            {
              label: '指定用户',
              value: 'a',
            },
            {
              label: '全班发送',
              value: 'b',
            },

          ]}
        />
        {
          userType == '' || userType == 'a' ?
            <ProFormTextArea
              wrapperCol={{ span: 12 }}
              fieldProps={{
                onChange,
                value: ipt,
                rows: 4,
                showCount: { formatter: () => `共${ipt !== '' ? count : 0}个用户` }
              }}
              rules={[
                { required: true, message: '请输入发放的手机号' },
                {
                  validator: async (_, value) => {
                    if (value && ruleObj.help !== '') {
                      return Promise.reject(new Error(ruleObj.help));
                    }
                    return
                  }
                }
              ]}
              validateStatus={ruleObj?.rule}
              help={ruleObj?.help}
              ref={uref}
              initialValue={ipt}
              name="mobile"
              placeholder="手机号换行输入，每行1个手机号，最多支持500个用户同时发送"
              label="手机号" /> : null
        }
        <ProFormRadio.Group
          name="type"
          label="发放类型"
          fieldProps={{
            onChange: onchange1,
          }}
          initialValue="c"
          options={[
            {
              label: '悟空点评',
              value: 'c',
            },
            {
              label: '老师复盘',
              value: 'd',
            },

          ]}
        />
        <ProFormText
          width="md"
          name="sendCount"
          label="发放次数"
          // fieldProps={{
          //   value: value1,
          //   onChange: onChange
          // }}
          rules={[
            { required: true, message: "请输入1-30之间的正整数" },
            {
              validator: async (_, names) => {
                // console.log(names);
                const reg = /^[1-9]\d*$/
                if (names && !reg.test(names)) {
                  return Promise.reject(new Error('请输入1-30之间的正整数'));
                } else if (names && names < 1 || names > 30) {
                  return Promise.reject(new Error('请输入1-30之间的正整数'));
                } else {
                  return;
                }
              }
            }
          ]}
          placeholder="请输入1-30之间的正整数"
        />
        <div style={{ width: "54%", position: 'relative', margin: 'auto' }}>
          {
            sendType == 'c' ?
              <div style={{ position: 'absolute', right: "0" }}>点评到期时间为用户悟空对弈结束时间</div> : sendType == 'd' ?
                <div style={{ position: 'absolute', right: "0" }}>复盘到期时间为课程结束时间往后推7天</div> : null
          }
        </div>
      </ModalForm>
    </div >
  )
}
